package com.ethannhu.todaynews.component.content

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import com.ethannhu.repository.DefaultNetworkRepository
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.entity.response.Meta
import com.ethannhu.todaynews.entity.response.onSuccess
import com.ethannhu.todaynews.model.BaseViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import org.apache.commons.lang3.StringUtils

/**
 * 内容界面 ViewModel，Fragment就可以只处理 UI相关的东西了
 */
class ContentViewModel(private val categoryId: String?) : BaseViewModel() {
    var lastId: String? = null


    private val _data = MutableSharedFlow<Meta<Content>>()
    val data: Flow<Meta<Content>> = _data

    private val _previewMedia = MutableSharedFlow<PreviewMediaPageData>()
    val previewMedia: Flow<PreviewMediaPageData> = _previewMedia

    private val _toArticleDetail = MutableSharedFlow<String>()
    val toArticleDetail: SharedFlow<String> = _toArticleDetail

    private val _toVideoDetail = MutableSharedFlow<String>()
    val toVideoDetail: SharedFlow<String> = _toVideoDetail

    fun loadMore(lastId: String? = null) {
        this.lastId = lastId
        viewModelScope.launch(coroutineExceptionHandler) {
            //这个categoryId服务端其实没用到，只是示范
            DefaultNetworkRepository.contents(lastId, categoryId = categoryId)
                .onSuccess(viewModel) {
                    _data.emit(it)//数据变更了，另一边的 Activity和 Fragment 都会收到通知
                }
        }
    }

    fun previewMedias(view: RecyclerView, medias: List<String>, position: Int) {
        viewModelScope.launch {
            _previewMedia.emit(
                PreviewMediaPageData(view, medias, position)
            )
        }
    }

    // 列表 item点击
    fun itemClick(item: Content) {
        viewModelScope.launch {
            if (StringUtils.isNotBlank(item.uri)) {
                _toVideoDetail.emit(item.id!!)
            } else {
                _toArticleDetail.emit(item.id!!)
            }
        }

    }

}